const Router = require('koa-router')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const { User } = require('@/app/models/user')
const { Auth } = require('@/middleware/auth')
const { security } = require('@/config')
const { generateToken } = require('@/utils/util')
const { RegisterValidator, LoginValidator,NotEmptyValidator } = require('@/utils/validator')

const router = new Router({
  //统一这是前缀
  prefix: '/api/v1/user' 
})
//注册
router.post('/register',async ctx => {
  const v = await new RegisterValidator().validate(ctx)
  const userInfo = {
    email: v.get('body.email'),
    password: v.get('body.password'),
    nickname: v.get('body.nickname'),
  }
  await User.create(userInfo)
  ctx.body = global.responseData(null, '注册成功')
})
//获取token
router.post('/getToken',async ctx => {
  const v = await new LoginValidator().validate(ctx)
  const user = await User.findOne({
    where: {
      email: v.get('body.account')
    }
  })
  if (!user) {
    ctx.body = global.responseData(null, '账号不存在', '404')
    return
  }
  const correct = bcrypt.compareSync(v.get('body.password'), user.password)
  if(!correct){
    ctx.body = global.responseData(null, '密码不正确','404')
    return
  }
  ctx.body = global.responseData(generateToken(user.id, Auth.USER), '登录成功')
})

//刷新token
router.post('/refreshToken',async ctx => {
  const v = await new NotEmptyValidator().validate(ctx,{
    token: 'refreshToken'
  })
  let refreshToken = v.get('body.refreshToken')
  if(Auth.verifyToken(refreshToken)){
    let {uid, scope} = jwt.verify(refreshToken,security.secretKey)
    ctx.body = global.responseData(generateToken(uid, scope), 'token刷新成功')
  }else{
    ctx.body = global.responseData(null, 'token失效，请重新登录','401')
  }
})

module.exports = router